package leetcode_top;

import org.junit.Test;

public class Ex8 {
    class Solution {
        public int myAtoi(String s) {
            if (s == null) return 0;
            // s = s.replaceAll(" ", "");
            int start =  0;
            while (start < s.length() && s.charAt(start) == ' ') {
                start++;
            }
            if (s.length() == 0 || start == s.length()) return 0;
            boolean flag = true;
            char c;
            if ((c = s.charAt(start)) == '+') {
                flag = true;
                start++;
            } else if (c == '-') {
                flag = false;
                start++;
            }
            s = s.substring(start); //后面的空格不能忽略，它也是结束符的一种
            if (s.length() == 0) {
                return 0;
            }
            char[] cs = s.toCharArray();
            int i = 0;
            while (i < cs.length && cs[i] == '0') {
                i++;
            }
            StringBuilder sb = new StringBuilder();
            for (; i < cs.length; i++) {
                if (!isDigit(cs[i])) break;
                sb.append(cs[i]);
            }
            long res = 0;
            for (i = 0; i < sb.length(); i++) {
                c = sb.charAt(i);
                res = res * 10 + c - '0';
                if (flag && res >= Integer.MAX_VALUE) {
                    return Integer.MAX_VALUE;
                } else if (!flag && -res <= Integer.MIN_VALUE) {
                    return Integer.MIN_VALUE;
                }
            } 
            if (flag) {
                if (res > Integer.MAX_VALUE) {
                    return Integer.MAX_VALUE;
                } else {
                    return (int)res;
                }
            } else {
                if (-res < Integer.MIN_VALUE) {
                    return Integer.MIN_VALUE;
                } else {
                    return (int)(-res);
                }
            }
        }


        public boolean isDigit(char c) {
            return c >= '0' && c <= '9';
        }
    }


    @Test
    public void test() {
        Solution s = new Solution();
        System.out.println(s.myAtoi("9223372036854775808"));
    }
}
